package org.belkodevelop.controller;

import org.belkodevelop.announcement.domain.Announcement;
import org.belkodevelop.announcement.dto.AnnouncementDto;
import org.belkodevelop.announcement.service.AnnouncementService;
import org.belkodevelop.form.FindRequestForm;
import org.dozer.DozerBeanMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.List;


@Controller
public class AnnouncementController {

    @Autowired
    private AnnouncementService announcementService;

    @Autowired
    DozerBeanMapper mapper;

    @RequestMapping(value = "/api/findAnnouncements.json",  headers="Accept=*/*")
    @ResponseBody
    public List<AnnouncementDto> getAnnouncements(@RequestBody FindRequestForm findRequestForm) {
        List<Announcement> announcementList = announcementService.findAnnouncement(findRequestForm.getFindRequest());

        List<AnnouncementDto> announcementDtoList = new ArrayList<AnnouncementDto>(announcementList.size());
        for (Announcement announcement: announcementList) {
            announcementDtoList.add(mapper.map(announcement, AnnouncementDto.class));
        }
        return announcementDtoList;
    }

    @RequestMapping("/announcementInfo/{id}.html")
    public ModelAndView announcementInfo(@PathVariable("id") Long id) {

        Announcement announcement = announcementService.getAnnouncement(id);

        announcementService.incrementRating(id);

        ModelAndView modelAndView = new ModelAndView("announcementInfo");
        modelAndView.addObject("announcement", announcement);
        return modelAndView;
    }

}
